<template>
  <section class="person-manage-main">
    <el-collapse-transition>
      <section v-show="searchshow" class="main-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input v-model.trim="listQuery.userName" placeholder="输入真实姓名搜索" class="search-input" @keyup.enter.native="handleFilter" />
        <section class="search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
          <!--          <span class="search-more" @click="searchshow = !searchshow">-->
          <!--            更多筛选条件-->
          <!--            <i class="el-icon-arrow-down" />-->
          <!--          </span>-->
        </section>
      </section>
    </el-collapse-transition>
    <el-collapse-transition>
      <section v-show="!searchshow" class="main-search separate">
        <section class="search-inner">
          <el-row>
            <el-col :span="12">
              <section class="search-inner-item">
                <div class="item-label">真实姓名</div>
                <el-input v-model.trim="search.userName" style="width: 90%;" class="filter-item" placeholder="请输入真实姓名搜索" />
              </section>
            </el-col>
            <el-col :span="12">
              <section class="search-inner-item">
                <div class="item-label">证件号码</div>
                <el-input v-model.trim="search.userIdnumber" style="width: 90%;" class="filter-item" placeholder="请输入证件号码搜索" />
              </section>
            </el-col>
            <el-col :span="12">
              <section class="search-inner-item">
                <div class="item-label">提交时间</div>
                <el-date-picker
                  v-model="search.time"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  clearable
                  :style="{ width: '90%' }"
                  type="datetimerange"
                  format="yyyy-MM-dd HH:mm"
                  value-format="yyyy-MM-dd HH:mm:ss"
                />
              </section>
            </el-col>
          </el-row>
        </section>
        <section class="search-btn">
          <el-button type="primary" @click="handleFilter">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
          <span class="search-more" @click="searchshow = !searchshow">
            精简筛选条件
            <i class="el-icon-arrow-up" />
          </span>
        </section>
      </section>
    </el-collapse-transition>

    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>学员管理</span>
      </section>
      <section class="main-buttons-btns">
        <el-button style="margin-left: 10px" @click="hadnleExport">导入</el-button>
        <el-button
          style="margin-left: 10px"
          @click="
            () => {
              $router.back()
            }
          "
        >返回</el-button>
      </section>
    </section>
    <!-- <div class="classify-tab">
      <el-tabs v-model="signStatus" @tab-click="handleTabClick">
        <el-tab-pane v-for="item in dict.AUDITRESULT" :key="item.dictValue" :label="item.dictName" :name="item.dictValue" />
      </el-tabs>
    </div> -->

    <section class="main-table">
      <!--      报名管理-->
      <v-table :list="list" :tag="tag" :list-loading="listLoading" :filter-column="filtercolumn" :selection="false">
        <!-- <el-table-column
          v-if="signStatus === 'AUDITRESULT01'"
          label="操作"
          fixed="right"
          align="center"
          min-width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleCheck(scope.row)">审核 </el-button>
          </template>
        </el-table-column> -->
      </v-table>

      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </section>

    <el-dialog title="审核" :visible.sync="centerDialogVisible" width="50%" center :close-on-click-modal="false" :destroy-on-close="true">
      <div>
        <section class="user-con"><span>姓名：</span>{{ userInfo.userName }}</section>
        <section v-if="userInfo.phoneNum" class="user-con"><span>手机号：</span>{{ userInfo.phoneNum }}</section>
        <section v-if="userInfo.idCard" class="user-con"><span>证件号：</span>{{ userInfo.idCard }}</section>
        <section v-if="userInfo.location" class="user-con"><span>所在地区：</span>{{ userInfo.location }}</section>
        <section v-for="(item, index) in registInfoForm" :key="index" style="margin-bottom: 20px">
          <section class="information-list" style="margin-bottom:10px">
            <span>{{ item.name }}:</span>
            <template v-if="item.srlx === 'img'">
              <el-image
                v-for="i in item.value ? item.value.split(',') : []"
                :key="i"
                class="comment-img"
                :z-index="99999"
                :src="view + i"
                :preview-src-list="[view + i]"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>
            </template>
            <template v-else>{{ item.value }}</template>
          </section>
        </section>
        <el-radio-group v-model="radio">
          <el-radio label="AUDITRESULT02">审核通过</el-radio>
          <el-radio label="AUDITRESULT03">审核不通过</el-radio>
        </el-radio-group>
        <el-input v-model="remark" style="margin-top:10px; " type="textarea" placeholder="请输入说明" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            centerDialogVisible = false
            remark = ''
          "
        >取 消</el-button>
        <el-button type="primary" @click="handleCommit('noseries')">确 定</el-button>
        <el-button type="primary" @click="handleCommit('series')">提交并审核下一条</el-button>
      </span>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogUploadVisible"
      title="上传文件"
      center
      width="500px"
      @close="handleClosed"
    >
      <el-upload
        ref="upload"
        v-loading="loadingUpload"
        element-loading-text="正在上传请稍后"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :auto-upload="false"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :action="uploadaction"
        :headers="uploadHeaders"
        :data="uploadData"
        accept=".xls, .xlsx"
        class="upload-demo"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          只能上传.xls,.xlsx
          <el-button type="text" @click="handleDownload">下载模板</el-button>
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" type="primary" @click="handleClosed">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="submitUpload()">确认</el-button>
      </span>
    </el-dialog>
  </section>
</template>
<script>
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import Pagination from '@/components/Pagination'
import VTable from '@/components/Table'
import { queryPage, getDictByCode, courseDetails, signDetails, aduit } from '../api'
import permission from '@/directive/permission/index.js'
import CryptoJS from '@/utils/aesJiaJM'
import { exportSign, importSign } from '@/utils/fileImportOrExportSign'
export default {
  name: 'StudentMangeIndex',
  components: { Pagination, VTable },
  directives: { permission, elDragDialog },
  data() {
    return {
      uploadData: {
        areaId: this.$route.query.id
      },
      uploadaction: '/API-ENTERPRISE-BACKEND/backend/areaDefinition/templateImport',
      uploadHeaders: { ttsxbwqm: '', ttsxsjzc: '', ttsxyhcs: '' },
      loadingUpload: false,
      dialogUploadVisible: false,
      classId: '', // 班级id
      id: '',
      listQuery: {
        page: 1,
        limit: 10,
        userName: ''
      },
      searchshow: true,
      search: {
        userName: '',
        userIdnumber: '',
        time: '',
        deptIds: []
      },
      list: [{}],
      total: 0,
      listLoading: false,
      view: '/API-DOCUMENT/document/file/download?id=',
      basisname: '',
      centerDialogVisible: false,
      dict: {
        AUDITRESULT: [] // 报名审核状态
      },
      remark: '',
      radio: '',
      selectRow: {},
      registInfoForm: {},
      registInfo: {}, // 报名表信息
      userInfo: {
        userName: '',
        phoneNum: '',
        idCard: '',
        location: ''
      },
      tag: 'performanceManagement'
    }
  },
  async created() {
    if (!this.$route.query.id) {
      this.$message({
        showClose: true,
        message: '参数异常！',
        type: 'warning',
        onClose: () => {
          this.$router.back()
        }
      })
      return
    } else {
      this.classId = this.$route.query.id
      await this.init()
    }
  },
  methods: {
    submitUpload() {
      if (this.$refs['upload'].uploadFiles.length === 0) {
        this.$message.error('请上传文件')
      } else {
        this.loadingUpload = true
        this.uploadHeaders = importSign({}, { areaId: this.$route.query.id })
        // this.uploadHeaders = importSign({}, {})
        setTimeout(() => {
          this.$refs.upload.submit()
        }, 1000)
      }
    },
    handleDownload() {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = '/API-ENTERPRISE-BACKEND/backend/areaDefinition/downloadTemplate' + exportSign({ areaId: this.classId }).paramStr
      link.setAttribute('download', '学员管理模板.xlsx')
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    uploadError(err) {
      this.loadingUpload = false
      this.$message.error(err || '网络异常')
    },
    uploadSuccess(data) {
      this.loadingUpload = false
      if (data.code === '200') {
        this.$message({
          message: '导入成功',
          type: 'success'
        })
        this.dialogUploadVisible = false
        this.uploadQuesDialogVisible = false
        this.$refs.upload.clearFiles()
        this.init()
      } else {
        this.$message.error(data.msg || '网络异常')
        if (data.data.fileid) {
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = '/API-ENTERPRISE-BACKEND/backend/areaDefinition/downloadCheckFile' + exportSign({ errorId: data.data.fileid }).paramStr
          link.setAttribute('download', '学员管理模板.xlsx')
          link.setAttribute('target', '_blank')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
        this.$refs.upload.clearFiles()
        if (data.data) {
          this.uploadErrorList = data.data
          this.dialogUploadErrorTextVisible = true
        }
      }
    },
    hadnleExport() {
      this.dialogUploadVisible = true
    },
    handleClosed() {
      this.dialogUploadVisible = false
      this.loadingUpload = false
      this.uploadQuesDialogVisible = false
      this.$refs.upload.clearFiles()
    },
    async init() {
      await this.getList()
    },
    /**
     * 班级详情
     */
    getData() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        courseDetails({ id: this.classId })
          .then((res) => {
            loading.close()
            if (res.data.data.registInfo) {
              this.registInfo = JSON.parse(res.data.data.registInfo) || ''
              /* const arr = this.registInfo
              for (const i in arr) {
                this.registInfoForm[arr[i].code] = ''
              }*/
            }
            resolve()
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },

    getDetail() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        signDetails({ id: this.id })
          .then((res) => {
            loading.close()
            if (res.data.code === '200' && res.data.data) {
              this.userInfo.userName = res.data.data.userName
              this.userInfo.phoneNum = CryptoJS.$aesJieM(res.data.data.phoneNum)
              this.userInfo.location = res.data.data.location
              this.userInfo.idCard = CryptoJS.$aesJieM(res.data.data.idCard)
              if (res.data.data.formName) {
                this.registInfoForm = JSON.parse(res.data.data.formName).slice(3)
                /* console.log(JSON.p arse(JSON.stringify(data)), 7777)
                this.registInfoForm = JSON.parse(JSON.stringify(data))*/
                /* for (const key in this.registInfoForm) {
                  this.registInfoForm[key] = data[key]
                }*/
              }
              this.centerDialogVisible = true
            }
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },

    filtercolumn(scope, item) {
      if (item === 'authValue') {
        return `${this.basisname}：${scope.row[item]}`
      } else if (item === 'idCard' || item === 'phoneNumber') {
        return CryptoJS.$aesJieM(scope.row[item])
        
      } else {
        return scope.row[item]
      }
    },

    handleReset() {
      this.listQuery.page = 1
      this.listQuery.userName = ''
      for (const i in this.search) {
        if (this.search['' + i + ''] instanceof Array) {
          this.search['' + i + ''] = []
        } else {
          this.search['' + i + ''] = ''
        }
      }
      this.getList()
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    async handleCheck(row) {
      this.radio = row.status || '0'
      this.selectRow = row
      this.id = row.id
      // await this.getData(row.id)
      await this.getDetail()
    },
    handleCommit(type) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        aduit({
          id: this.id,
          authStatus: this.radio,
          authReason: this.remark
        })
          .then((res) => {
            loading.close()
            if (res.data.code === '200') {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.remark = ''
              this.centerDialogVisible = false
              if (type === 'series') {
                if (res.data.data.id) {
                  this.id = res.data.data.id
                  this.getDetail()
                } else {
                  this.$message({
                    message: '没有下一条数据！',
                    type: 'warning',
                    duration: 1500
                  })
                  this.getList()
                }
              } else {
                this.getList()
              }
            }
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    /* handleView(row) {
      this.$router.push({ path: this.$filterPath('check'), query: { i: row.id, type: 'view' }})
    },*/

    getList(obj) {
      this.listLoading = true
      var query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        areaId: this.classId
      }
      if (this.searchshow) {
        query['userName'] = this.listQuery.userName
      } else {
        query['userName'] = this.search.userName
        query['userIdnumber'] = this.search.userIdnumber
        query['deptIds'] = this.search.deptIds.length > 0 ? this.search.deptIds.join(',') : ''
        query['startcrtTime'] = this.search.time && this.search.time.length > 0 ? this.search.time[0] : ''
        query['endcrtTime'] = this.search.time && this.search.time.length > 0 ? this.search.time[1] : ''
      }
      return new Promise((resolve, reject) => {
        queryPage(query)
          .then((response) => {
            this.list = response.data.data.rows
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch((error) => {
            reject(error)
            this.listLoading = false
          })
      })
    }
  }
}
</script>
<style lang="scss">
@import '@/styles/mixin.scss';

.person-manage-main {
  padding: 10px;
  .upload-demo {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  .el-upload-dragger {
    width: 100%;
  }
  .el-upload__tip {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .main-search {
    background-color: #fff;
    padding: 0 10px;
    .svg-container {
      padding: 0 5px 0 10px;
      color: #bfced6;
      vertical-align: middle;
      display: inline-block;
    }
    .search-input {
      width: 60%;
      position: relative;
      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }
      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;
        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }
    .search-btn {
      display: inline-block;
      float: right;
      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }
      .search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }

    &.separate {
      .search-inner {
        padding-top: 10px;
        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }
          .el-input {
            position: relative;
            &.el-date-editor input {
              padding-left: 30px;
            }
            .el-input__inner {
              border: none;
              padding: 0;
            }
            &:after {
              content: '';
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }
      .search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }
  .classify-tab {
    width: 100%;
    margin-bottom: 10px;
    padding: 0 10px;
    background-color: #fff;
    display: flex;
    border-radius: 4px;
    .el-tabs__nav-wrap::after {
      display: none;
    }
    .el-tabs__header {
      margin: 0;
    }
  }
  .main-buttons {
    display: flex;
    line-height: 36px;
    margin-top: 10px;
    .main-buttons-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }
  .user-con {
    span {
      margin-right: 15px;
      width: auto;
    }
    margin-bottom: 20px;
  }
  .information-list {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    span {
      //min-width: 60px;
      margin-right: 15px;
      width: auto;
    }
    .el-image {
      width: 80px;
      height: 80px;
      margin-right: 15px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
